package com.ray.service;


import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.google.appengine.api.search.query.ExpressionParser.name_return;
import com.ray.bean.CompanyMaterialTableBean;
import com.ray.bean.DisplayViewBean;
import com.ray.bean.EquipmentChangeOrderBean;
import com.ray.bean.OrderBean;
import com.ray.bean.ProductionExceptionBean;
import com.ray.bean.PutOutOrderBean;
import com.ray.bean.QCReportBean;
import com.ray.bean.ReportBean;
import com.ray.bean.TurnoverBean;
import com.ray.bean.UserProcessDisplayViewBean;
import com.ray.bean.WarehouseInOutDetailBean;
import com.ray.bean.WarehouseInSumMoneyBean;
import com.ray.mapper.DisplayViewMapper;
import com.ray.mapper.OrderMapper;
import com.ray.mapper.PurchaseOrderMapper;
import com.ray.pojo.MyUser;
import com.ray.pojo.PurchaseOrderDetailPojo;
import com.ray.util.ReturnStringUtil;
import com.ray.util.StringUtil;
import com.ray.util.redis.RedisCache;
import com.ray.util.redis.RedisKey;
import com.thoughtworks.xstream.mapper.Mapper.Null;

import net.sf.json.JSONArray;


/**
 * 显示屏
 * @author natelu
 *
 */
@Service
public class DisplayViewService {

	@Autowired
	DisplayViewMapper displayViewMapper;
	@Autowired
	PurchaseOrderMapper purchaseOrderMapper;
	@Autowired
	PermissionService permissionService;
	@Autowired
	WorkshopService workshopService;
	@Autowired
	PutOutServiceNew putOutServiceNew;
	@Autowired
	WarehouseService warehouseService;
	@Autowired
	ProcedureService procedureService;
	@Autowired
	OrderService orderService;
	
	
	/**
	 * 设置登录令牌
	 * @param myUser
	 * @return
	 */
	public String setDisplayViewToken(MyUser myUser) {
		String token=StringUtil.getUUID();
		displayViewMapper.setDisplayViewToken(myUser.getCompany(),myUser.getUserId(),token);
		return token;
	}
	
	
	/**
	 * 校验显示屏登录状态
	 * @param request
	 * @param token
	 * @throws IOException 
	 */
	public MyUser checkLogin(HttpServletRequest request, String token) throws IOException {
		MyUser myUser=(MyUser) request.getSession().getAttribute("userLogin");
		//如果用户没有登录
		if(myUser==null) {
			myUser=displayViewMapper.getMyUserByToken(token);
			Assert.notNull(myUser,"用户失效");
			myUser.setPermissionList(permissionService.getUserPermissionBeanByUserId(myUser.getUserId()));
			request.getSession().setAttribute("userLogin", myUser);	
		}
		return myUser;
	}

	
	/**
	 * 通过redis产能看板信息
	 * @param map
	 * @return
	 * @throws ParseException
	 */
	public Map getTrunoverDutyMantissaFromRedis(Map map,MyUser myUser) throws ParseException{
		String company=map.get("loginCompany").toString();
		String redisKey=RedisKey.COMPANY_WORKSHOP_CAPACITY_DISPLAY_VIEW+company;
		Map returnMap=(Map) RedisCache.getDataFromRedis(redisKey);
		Object deptId=map.get("deptId");
		Object workShopId=map.get("workShopId");
		map.remove("deptId");
		map.remove("workShopId");
		if(null==returnMap) {
			returnMap=this.getTrunoverDutyMantissa(map, myUser);
			if(null==returnMap) {
				returnMap=new HashMap();
			}
			RedisCache.setDataToRedis(redisKey, returnMap, RedisKey.COMPANY_WORKSHOP_CAPACITY_DISPLAY_VIEW_EXPIRETIME);
		}
		List<DisplayViewBean> productionList=(List<DisplayViewBean>) returnMap.get("productionList");
		//如果要过滤部门
		if(null!=deptId && !"".equals(deptId.toString()) && null!=productionList) {
			productionList=productionList.stream().filter(pp->pp.getDeptId().equals(deptId.toString())).collect(Collectors.toList());
		}
		//如果要过滤车间
		//如果要过滤车间
		String workShopIdListStr=map.get("workShopIdList")==null?"":map.get("workShopIdList").toString();
		if(!"".equals(workShopIdListStr)) {
			 JSONArray jsonArray=JSONArray.fromObject(workShopIdListStr);
			 List<String>  workShopIdList = jsonArray.subList(0, jsonArray.size());
			 productionList=productionList.stream().filter(pp->workShopIdList.contains(pp.getWorkShopId())).collect(Collectors.toList());
		}else if(null!=workShopId && !"".equals(workShopId.toString()) && null!=productionList) {
			productionList=productionList.stream().filter(pp->pp.getWorkShopId().equals(workShopId.toString())).collect(Collectors.toList());
		}
		returnMap.put("productionList", productionList);
		return returnMap;
	}

	/**
	 * 获取显示屏的异常数据
	 * @param deptId(部门id 非必传)
	 * @param workShopId(车间id 非必传)
	 * @param map
	 * @return
	 */
	public Map getTrunoverDutyMantissa(Map map,MyUser myUser) {
		Map returnMap=new HashMap<>();
		//如果是经理
		if(("1".equals(myUser.getDuty()) || 1==myUser.getIsManager()) && !"方氏板材二线".equals(myUser.getCompany())) {
			List<PutOutOrderBean> putOutList=this.getPutoutOrderNoPage(map);
			returnMap.put("putOutList", putOutList);
			List<PurchaseOrderDetailPojo> purchaserOrderList =new ArrayList<PurchaseOrderDetailPojo>();
	        returnMap.put("purchaseList", purchaserOrderList);
		}
		//更正参数名
		map.put("workShop", map.get("workShopId"));
		returnMap.put("productionList", workshopService.getTrunoverDutyMantissa(map));
		return returnMap;
	}

    //获取拖期采购单信息
	public List<PurchaseOrderDetailPojo> getPurchaseOrder(Map map) {
		Map purchaeMap=new HashMap(map);
//		purchaeMap.put("isFinish", "0");
//		purchaeMap.put("status", 1);
//		purchaeMap.put("type", 1);
		return displayViewMapper.getPurchaseOrderByPageData(purchaeMap);
	}


	/**
	 * 获取外协拖期数据
	 * @param map
	 * @return
	 */
	private List<PutOutOrderBean> getPutoutOrderNoPage(Map map) {
		Map putoutMap=new HashMap<>(map);
		putoutMap.put("isFinish", 2);
		putoutMap.put("status", 1);
		putoutMap.put("delay", 10000000);
		return putOutServiceNew.getPutoutOrderNoPage(putoutMap);
	}


	/**
	 * 获取仓库超出库存上限的物料
	 * @param map
	 * @return
	 */
	public List<CompanyMaterialTableBean> warehouseBeyondMax(Map map) {
		return warehouseService.warehouseBeyondMax(map);
	}

    /**
     * 获取超出库存下限物料
     * @param map
     * @return
     */
	public List<CompanyMaterialTableBean> warehouseBeyondMin(Map map) {
		return warehouseService.warehouseBeyondMin(map);
	}


	/**
	 * 获取呆滞物料
	 * @param map
	 * @return
	 */
	public List<CompanyMaterialTableBean> getStillnessMaterial(Map map) {
		return warehouseService.getStillnessMaterial(map);
	}


	/**
	 * 获取收款拖期数据
	 * @param map
	 * @return
	 */
	public List<WarehouseInOutDetailBean> getReceivablesDelayData(Map map) {
		return warehouseService.getReceivablesDelayData(map);
	}


	/**
	 *  获取换单记录
	 * workShop 车间id
	 * equipmentNo 设备编号
	 * orderId 订单编号
	 * userId 操作人
	 * @param map
	 * @return
	 */
	public List<EquipmentChangeOrderBean> getEquipmentChangeOrderRecord(Map map) {
		List<String> orderList=new ArrayList<>();
		if(map.get("workShop") != null || null!=map.get("equipmentNo") ||  null!=map.get("orderId") ||  null!=map.get("userId")) {
			if(null!=map.get("orderId") && "".equals(map.get("orderId"))) {
				orderList.add(map.get("orderId").toString());
			}else if(map.get("workShop") != null && !"".equals(map.get("workShop"))){
				List<TurnoverBean> tuenList=workshopService.getTrunoverNewList(map);
				orderList=tuenList.stream().map(TurnoverBean::getOrderId).collect(Collectors.toList());
				if(orderList.size()<=0) {
					return null ;
				}
			}
			map.put("orderIdList", orderList);
			return displayViewMapper.getEquipmentChangeOrderRecord(map);
		}else {
			return displayViewMapper.getEquipmentChangeOrderRecordLast(map);
		}
	}


	/**
	 * 获取qc看板内容
	 * @param map
	 * @return
	 */
	public List<QCReportBean> getQCDisplay(Map map) {
		return procedureService.getQCDisplay(map);
	}


	/**
	 * 获取人员工序看板数据
	 * @param map
	 * @return
	 */
	public List<UserProcessDisplayViewBean> getUserProcessDisplayViewData(Map map) {
		return displayViewMapper.getUserProcessDisplayViewData(map);
	}


	/**
	 * materialTypeArray 物料类型字符串
	 * @param map
	 * @return
	 */
	public String setMaterialIsShow(Map map) {
        StringUtil.checkIsTrue(map, "materialTypeArray", "未获取到参数");
        displayViewMapper.deleteMaterialIsShow(map);
		int  row = displayViewMapper.setMaterialIsShow(map);
		Assert.isTrue(row>0,ReturnStringUtil.OPERATION_ERROR);
		return ReturnStringUtil.OPERATION_SUCCESS;
	}


	/**
	 * 获取物料显示
	 * @param map
	 * @return
	 */
	public Map getMaterialIsShow(Map map) {
		return displayViewMapper.getMaterialIsShow(map);
	}


	/**
	 * 获取订单详情
	 * @param map
	 * @return
	 * @throws CloneNotSupportedException 
	 * @throws ParseException 
	 */
	public List<Map> getOrderMatchingDetail(Map map) throws ParseException, CloneNotSupportedException {
		return orderService.getOrderMatchingDetailFromRedis(map);
	}
	
}
